<script setup lang="ts">
import { ref, onMounted } from "vue";
import { fabric } from "fabric";

const canvas = ref(null);

onMounted(() => {
  var canvas = new fabric.Canvas("canvasfabric", { selection: false });
  fabric.Object.prototype.originX = fabric.Object.prototype.originY = "center"; //所有图形的绘制起点都是中间点

  const initEvent = () => {
    //   监听鼠标点击事件
    canvas.on("mouse:down", (options) => {
      console.log(
        `x轴坐标: ${options.e.clientX};    y轴坐标: ${options.e.clientY}`
      );
    });
  };

  const createRect = () => {
    var geometry = new fabric.Rect({
      name: "rect",
      top: 50,
      left: 50,
      width: 50,
      height: 50,
      fill: "red", //填充
      rx: 20, //水平圆角
      ry: 20, //垂直圆角
      originX: "center", //top,left坐标的水平起点
      originY: "center", //top,left坐标的垂直起点

      stroke: "#0000ff",
      strokeWidth: 1,
      objectCaching: false,
      transparentCorners: false,
      cornerColor: "red",
      hasBorders: true,
      hasControls: true,
      //   lockMovementX:true,//禁止水平方向移动
      //   lockMovementY:true,//禁止垂直方向移动
      //   angle: 30, //旋转角度
      //   backgroundColor: "#ccc", //背景色
      //   borderDashArray: [1, 3],  //指定对象边框的破折号图案的数组（hasBorder 必须为真）,设置为虚线
      borderOpacityWhenMoving: 0.1, //拖拽移动时边框线的透明度
      borderScaleFactor: 3, //边框线条的粗细
    });

    geometry?.on("selected", function (options: any) {
      console.log("选中矩形啦", options);
      //启动canvas上的自定义事件
      setTimeout(() => {
        console.log("选中矩形啦2", options);
        options.target.canvas.discardActiveObject();
        this.canvas.requestRenderAll();
      }, 1000);
      options.target.canvas.fire("custom:activeCameraObject", this);
    });

    return geometry;
  };

  initEvent();
  const rect = createRect();
  console.log(rect);
  canvas.add(rect);

  canvas.on("object:modified", function (e) {
    console.log(`修改了:${e.target.name}`, e);
  });

  //启动canvas上的自定义事件
  canvas.on("custom:activeCameraObject", function (e) {
    console.log(`自定义事件:custom:activeCameraObject`, e);
  });
});
</script>

<template>
  <a
    target="_blank"
    href="http://k21vin.gitee.io/front-end-data-visualization/#/fabric/fabric-demo/fabric-createRect"
    >推荐教程</a
  >
  |
  <a
    target="_blank"
    href="https://gitee.com/k21vin/front-end-data-visualization/blob/master/src/views/FabricJS/Basic/pages/Stated/Stated.vue"
    >配套代码</a
  >
  |
  <a target="_blank" href="http://fabricjs.com/docs/">fabricjs文档</a>

  <canvas id="canvasfabric" width="800" height="800" ref="canvas"></canvas>
</template>

<style lang="scss"></style>
